package com.LeeCode;

import java.util.ArrayList;
import java.util.List;

/**
 * 组合总和 III
 */

public class Code216 {
    public static void main(String[] args) {
        int k = 9, n = 1;
        System.out.println(new Code216().combinationSum3(k, n));
    }

    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ans = new ArrayList<>();
        if (n > 45) return ans;
        backtrace(1, n, k, new ArrayList<>(), ans);
        return ans;
    }

    private void backtrace(int index, int n, int k, List<Integer> cur, List<List<Integer>> ans) {
        if (k == 0) {
            if (n == 0) {
                ans.add(new ArrayList<>(cur));
            }
            return;
        }

        if (index > 9) return;

        for (int i = index; i <= 9; i++) {
            if (i <= n) {
                cur.add(i);
                backtrace(i + 1, n - i, k - 1, cur, ans);
                cur.remove(cur.size() - 1);
            }
        }
    }
}
